package br.com.lumis.saas.service.consumerclient.postloadprocessor;

import lumis.doui.source.ISourceData;
import lumis.doui.source.Source;
import lumis.doui.source.TabularData;
import lumis.doui.source.TabularSource;
import lumis.doui.source.postloadprocessor.IPostLoadProcessor;
import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.util.ITransaction;

import org.w3c.dom.Node;

import br.com.lumis.saas.SaasRequestParameters;
import br.com.lumis.saas.util.Configuration;

public class LumisUnitsPostLoadProcessor implements IPostLoadProcessor {
	public void processSource(SessionConfig sessionConfig, Source source,
			Node parametersNode, ITransaction transaction)
			throws PortalException {

		Configuration config =  Configuration.getInstance();
		TabularSource<?> tabularSource = (TabularSource<?>) source;
		TabularData tabularData = tabularSource.getData();
		if (tabularData.getRows().size() == 0)
			return;

		if (tabularData.getRows().get(0).get(SaasRequestParameters.PAGEVIEW,
				Double.class) != null) {
			double unitsPages = tabularData.getRows().get(0).get(
					SaasRequestParameters.PAGEVIEW, Double.class) / Double.valueOf(config.getProperty("saas.unit.pageview"));
			double unitsTransfer = tabularData.getRows().get(0).get(
					SaasRequestParameters.TRANSF, Double.class) / Double.valueOf(config.getProperty("saas.unit.transf"));
			double unitsStorage = tabularData.getRows().get(0).get(
					SaasRequestParameters.STORAGE, Double.class) / Double.valueOf(config.getProperty("saas.unit.storage"));

			double mayor = unitsPages;

			if (unitsTransfer > mayor)
				mayor = unitsTransfer;
			if (unitsStorage > mayor)
				mayor = unitsStorage;

			for (ISourceData row : tabularData.getRows()) {
				row.put(SaasRequestParameters.LUMISUNITS, Math.ceil(mayor));

			}
		}

	}
}
